// This is the main DLL file.

#include "stdafx.h"
#include <iostream>
#include "vix.h"
#include "VirtualOps.Vix.h"

namespace VirtualOpsVix {

    void VixDiscoveryProc(VixHandle jobHandle,
        VixEventType eventType,
        VixHandle moreEventInfo,
        void *clientData)
    {
        VixError err = VIX_OK;
        //VixHandle jobHandle = VIX_INVALID_HANDLE; // Mistype!
        //VixHandle vmHandle = VIX_INVALID_HANDLE;
        char *url = NULL;
        // Check callback event; ignore progress reports.
        if (VIX_EVENTTYPE_FIND_ITEM != eventType) {
            return;
        }

        // Found a virtual machine.
        err = Vix_GetProperties(moreEventInfo,
            VIX_PROPERTY_FOUND_ITEM_LOCATION,
            &url,
            VIX_PROPERTY_NONE);
        if (VIX_OK != err) {
            // Handle the error...
            cout<< "Error " << err <<endl;
            goto abort;
        }
        printf("\nFound virtual machine: %s", url);
abort:
        // Vix_ReleaseHandle(jobHandle); BUG! 
        Vix_FreeBuffer(url);
    }

    int VixServer::Discover()
    {
        VixHandle jobHandle = VIX_INVALID_HANDLE;
        VixHandle hostHandle = VIX_INVALID_HANDLE;
        VixError err;
        // have to use WORKSTATION and 1.1 to use NULL username and password
        jobHandle = VixHost_Connect(VIX_API_VERSION,
            VIX_SERVICEPROVIDER_VMWARE_WORKSTATION,
            0, // hostName
            0, // hostPort
            0, // userName
            0, // password,
            0, // options
            VIX_INVALID_HANDLE, // propertyListHandle
            NULL, // callbackProc
            NULL); // clientData
        err = VixJob_Wait(jobHandle,
            VIX_PROPERTY_JOB_RESULT_HANDLE,
            &hostHandle,
            VIX_PROPERTY_NONE);
        if (VIX_OK != err) {
            // Handle the error...
            cout<< "Error connecting" << err <<endl;
            goto abort;
        }

        Vix_ReleaseHandle(jobHandle);

        printf("\nLooking for running virtual machines");

        jobHandle = VixHost_FindItems(hostHandle,
            VIX_FIND_RUNNING_VMS,
            VIX_INVALID_HANDLE, // searchCriteria
            -1, // timeout
            VixDiscoveryProc,
            NULL);
        err = VixJob_Wait(jobHandle, VIX_PROPERTY_NONE);
        if (VIX_OK != err) {
            // Handle the error...
            cout << "Error discovering" << err << endl;
            //cout << Vix_GetErrorText(err, NULL);
            goto abort;
        } else { 
            cout << endl << "done!" << endl;
        }
abort:
        Vix_ReleaseHandle(jobHandle);
        VixHost_Disconnect(hostHandle);
        return 0;
    }
}
